/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package freechoicepn.test;

import freechoicepn.datamodel.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;


/**
 *
 * @author Tomas
 * 
 * Testuje ci pn siet je free choice
 * 
 * Pseudokod:
 * 
 * 1. vyberem miesto z mnoziny vsetkych miest PN siete - nazvem ho parent
 * 
 * 2. z miesta parent ziskam vsetky vystupne prechody - nazvem ich childs
 * 
 * 3. pre vsetky prechody v mnozine childs najdem dalsie vstupne miesta, ine ako 
 *    miesto parent - nazvem tuto mnozinu nextParents
 * 
 * 4. z kazdeho miesta v mnozine nextParents vyberiem mnozinu vsetkych vystupnych
 *    prechodov a nazvem ju nextChilds
 * 
 * 5. porovnam vsetky zosortovane nextChilds mnozniny s mnozinou childs
 *    Ak je siet typu free choice musia sa rovnat
 */
public class FreeChoice {
    
    // vrati true ak pn siet je free choice
    public static boolean Test(ArrayList<Place> places) {
        
        for (Place place : places) {
            
            ArrayList<Transition> childs = place.getOutTransitions();
            Collections.sort(childs);
            
            ArrayList<Place> nextParents = getNextParents(place, childs);
            
            for (Place nextParent : nextParents) {
                ArrayList<Transition> nextChilds = nextParent.getOutTransitions();
                Collections.sort(nextChilds);
                
                // ak sa mnoziny nerovnaju vrati sa false
                if (!childs.equals(nextChilds)) {
                    return false;
                }
            }
        }
       
        return true;
    }
    
    private static ArrayList<Place> getNextParents(Place parent, ArrayList<Transition> childs) {
        
        // do HashSet kolekcie sa neukladaju duplikatne prvky
        HashSet<Place> nextParents = new HashSet();
        
        for (Transition transition : childs) {
            ArrayList<Place> parents = transition.getInPlaces();
            parents.remove(parent);
            
            nextParents.addAll(parents);
        }
        
        return new ArrayList(nextParents);
    }
}
